import sys
import os

import made.contrib.libdeps
from made.contrib import compilersettings
from made import runtime

sys.path.append(runtime.toplevel_madefile().dir + "/houdini/make")
import list_link_libs

_built_libs = set("lib" + lib_name
    for lib_name in list_link_libs.getUnexpandedSmallDepsDict(
        only_put_built_libs_in_keys=True).keys())

def input_libs_for_libs(lib_names, is_for_dynamic):
    # TODO: Set use_framework=True on the mac?
    options = list_link_libs.computeLibDependenciesAndGetLinkOptions(
        lib_names,
        skip_listed=False,
        use_shared_crt=is_for_dynamic,
        use_framework=False)

    # TODO: For whatever reason, list_link_libs doesn't put the .a files on
    #       a single line.  It probably shouldn't ever be listing .a files
    #       here anyway.
    old_options = options
    options = []
    for option in old_options:
        if option.startswith("-l"):
            options.append(option)
        else:
            options.extend(option.strip().split())

    library_extensions = {
        True: compilersettings.cpp_compiler_chain.dynamic_library_extension(),
        False: compilersettings.static_library_extension()
    }

    # Note that on Linux the name includes the "lib" prefix.
    input_libs = []
    for option in options:
        is_dynamic = False
        full_path_to_static_library_or_none = None

        if compilersettings.cpp_compiler_chain.name == "msvc":
            name = option
            if os.path.isabs(option):
                full_path_to_static_library_or_none = option
                name = os.path.basename(name)
            else:
                is_dynamic = is_for_dynamic
        else:
            if option.startswith("-l"):
                name = "lib" + option[2:] + library_extensions[is_for_dynamic]
                is_dynamic = is_for_dynamic
            else:
                full_path_to_static_library_or_none = option
                name = os.path.basename(option)

        input_libs.append(made.contrib.libdeps.InputLibrary(
            name, is_built=os.path.splitext(name)[0] in _built_libs,
            is_dynamic=is_dynamic,
            full_path_to_static_library_or_none=
                full_path_to_static_library_or_none))

    return input_libs

